<?php
/**
 * connection model
 *
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.1
 */
class user_connection extends db_model {
    protected static $connection_types = Array(
      'wifi',
      'bluetooth'
    );
    protected $data = Array(
      'user_id' => NULL,
      'type' => NULL,
      'mac' => NULL,
      'lts' => NULL,
    );

    public function set($key, $value) {
        if (array_key_exists($key, $this->data)) {
            if (($key == 'type')
                && (!in_array($value, self::$connection_types))
            ) {
                throw new model_exception('Type does not match.');
            }
            else if ($key == 'mac') {
                $mac_regex_pattern = '/^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$/';
                if (!preg_match($mac_regex_pattern, $value)) {
                    throw new model_exception('MAC address format invalid.');
                }
            }

            $this->data[$key] = $value;
            return true;
        }
        else {
            throw new model_exception('Key not valid for model.');
        }
    }

    public function save() {
        foreach ($this->data as $key => $value) {
            if ($key == 'lts') {
                continue;
            }

            if ($value === NULL) {
                throw new model_exception(
                  'Saving not possible. Not all data given.'
                );
            }
        }

        $this->escape_data();

        $q = 'INSERT INTO user_connection '
            .'(user_id, type, mac) '
            .'VALUES ('
            .$this->data['user_id'].','
            .'\''.$this->data['type'].'\','
            .'\''.$this->data['mac'].'\') '
            .'ON DUPLICATE KEY UPDATE lts=CURRENT_TIMESTAMP';
        self::$dbc->query($q);

        return true;
    }

    public static function get_by_user_id_connection_type(
      $user_id,
      $connection_type
    ) {
        $q = 'SELECT * '
            .'FROM user_connection '
            .'WHERE user_id='.self::$dbc->escape($user_id).' AND '
            .'type=\''.self::$dbc->escape($connection_type).'\'';
        $result = self::$dbc->query_assoc($q);

        if (!is_array($result) || !count($result)) {
            throw new model_exception(
              'No '.$connection_type.' connection for user '.$user_id.'.'
            );
        }

        return new user_connection($result[0]);
    }

    public static function get_by_user_id($user_id) {
        $result = Array();
        
        foreach (self::$connection_types as $connection_type) {
            try {
                $result[$connection_type] = self::get_by_user_id_connection_type(
                  $user_id,
                  $connection_type
                );
            }
            catch (model_exception $e) {

            }
        }        

        return $result;
    }
}
?>